import { defineStore } from 'pinia'
import { ComponentSize } from 'element-plus'
import { store } from "../index"
import { setCssVar, underlineToHump } from '@/utils';
interface AppState {
  pageLoading: boolean,// 页面加载
  sizeMap: ComponentSize[],// 尺寸配置项
  currentSize: ComponentSize,// 当前尺寸
  layout: LayoutType,// 布局
  isDark: boolean,// 是否是暗黑模式
  collapse: boolean,// 侧边栏是否收缩
  theme: any,// 主题
  // theme: {
  //   topHeaderBgColor?: string;
  //   leftMenuBgColor?: string;
  // }
}

export const useAppStore = defineStore("app", {
  state: (): AppState => {
    return {
      sizeMap: ['default', 'large', 'small'],
      pageLoading: false,
      currentSize: "large",//当前尺寸
      layout: "classic",//布局
      isDark: false, // 是否是暗黑模式
      collapse: true,//侧边栏是否收缩
      theme: {
        // 左侧菜单背景颜色
        leftMenuBgColor: '#fff',
        // 头部背景颜色
        topHeaderBgColor: '#fff',
      },
    }
  },
  getters: {
    getCurrentSize(state) {
      return state.currentSize;
    },
    getPageLoading(state) {
      return state.pageLoading
    },
    getLayout(state) {
      return state.layout;
    },
    getCollapse(state) {
      return state.collapse;
    },
    getIsDark(state) {
      return state.isDark;
    },
    getSizeMap(state) {
      return state.sizeMap;
    },
    getTopHeaderBgColor(state) {
      return state.theme.topHeaderBgColor
    },
    getLeftMenuBgColor(state) {
      return state.theme.leftMenuBgColor
    }
  },
  actions: {
    setCurrentSize(size: ComponentSize) {
      this.currentSize = size;
    },
    setPageLoading(loading: boolean) {
      this.pageLoading = loading
    },
    setCollapse() {
      this.collapse = !this.collapse
    },
    setTopHeaderBgColor(color: string) {
      this.theme.topHeaderBgColor = color
    },
    setLeftMenuBgColor(color: string) {
      this.theme.leftMenuBgColor = color
    },
    // 切换黑暗模式
    setIsDark(isDark: boolean) {
      this.isDark = isDark
      if (!isDark) {
        // 设置主题
        document.documentElement.setAttribute("theme", "light");
        // element-plus主题
        document.querySelector("html")?.classList.remove("dark");
        document.querySelector("html")?.classList.add("light");
      } else {
        document.documentElement.setAttribute("theme", "dark");
        document.querySelector("html")?.classList.remove("light");
        document.querySelector("html")?.classList.add("dark");
      }
    },
    setCssVarTheme() {
      for (const key in this.theme) {
        setCssVar(`--${underlineToHump(key)}`, this.theme[key])
      }
    },
    // 初始化主题
    initTheme() {
      this.setIsDark(this.isDark)
      this.setCurrentSize(this.currentSize)
    }
  },
  persist: true,
})

export const useAppStoreWithOut = () => {
  return useAppStore(store)
}